#include "Reader.h"

namespace Lyt
{
	namespace IO
	{
		StreamReader::StreamReader(IStream *stream)
		{
			Stream=stream;
		}

		StreamReader::StreamReader(const WString FileName)
		{
			Stream=new FileStream(FileName, modeRead);
		}

		StreamReader::~StreamReader()
		{
			Close();
		}

		bool StreamReader::IsAvailable()const
		{
			return (Stream && Stream->IsAvailable());
		}

		void StreamReader::Close()
		{
			if (Stream) delete Stream;
			Stream=0;
		}

		WString StreamReader::Peek()
		{
			if (IsAvailable())
			{
				wchar_t Buffer;
				if (Stream->Peek(&Buffer, sizeof(wchar_t))>0) return WString(Buffer);
			}
			return L"";
		}

		WString StreamReader::Read()
		{
			if (IsAvailable())
			{
				wchar_t Buffer;
				if (Stream->Read(&Buffer, sizeof(wchar_t))>0) return WString(Buffer);
			}
			return L"";
		}

		WString StreamReader::ReadLine()
		{
			if (IsAvailable())
			{
				WString Result;
				wchar_t Buffer;
				do
				{
					if (Stream->Peek(&Buffer, sizeof(wchar_t))>0)
					{
						if (Buffer==L'\n')
						{
							Stream->Seek(sizeof(wchar_t), seekCurrent);
							return Result;
						}
						else if (Buffer==L'\r') Stream->Seek(sizeof(wchar_t), seekCurrent);
						else
						{
							int Count=Stream->Read(&Buffer, 2);
							if (Count>0) Result=Result+Buffer;
						}
					}
					else return Result;
				}
				while (IsAvailable());
				return Result;
			}
			return L"";
		}

		WString StreamReader::ReadToEnd()
		{
			if (IsAvailable())
			{
				int Size=(Stream->GetLength()-Stream->GetPosition())/sizeof(wchar_t);
				if (Size>0)
				{
					wchar_t* Buffer=new wchar_t[Size+1];
					if (Stream->Read(Buffer, Size*sizeof(wchar_t))<0) return L"";
					Buffer[Size]=0;
					return WString(Buffer);
				}
				else return L"";
			}
			return L"";
		}
	}
}